package org.bzjj.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import org.bzjj.log.MyLog;

public final class DBConnect {
	///**
	private static String URL = "jdbc:mysql://localhost:3306/vims";// "jdbc:mysql://w.rdc.sae.sina.com.cn:3307/app_"+SaeUserInfo.getAppName();使用主库的域名
	// 通过SaeUserInfo提供的静态方法获取应用的access_key和secret_key
	private static String Username = "root";// SaeUserInfo.getAccessKey();
	private static String Password = "root";// SaeUserInfo.getSecretKey();
	//*/
	
	private static String Driver = "com.mysql.jdbc.Driver";
	private static Connection conn = null;

	private static DBConnect connect = null;

	// 通过静态代码块注册数据库驱动，保证注册只执行一次
	static {
		try {
			// 注册驱动有如下方式：
			// 1.通过驱动管理器注册驱动，但会注册两次，并且会对类产生依赖。如果该类不存在那就报错了。
			// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			// 2.与3类似
			// System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
			Class.forName(Driver);// 推荐使用方式
		} catch (ClassNotFoundException e) {
			Logger logger=MyLog.getLog("DBConnect");
			logger.error("加载数据库驱动错误:"+e.getMessage());
		}
	}

	public static DBConnect getDBonnect() {

		if (connect == null) {
			// 给类加锁 防止线程并发
			synchronized (DBConnect.class) {
				if (connect == null) {
					connect = new DBConnect();
				}
			}

		}
		return connect;
	}

	private DBConnect() {
	}

	// 获得连接
	public Connection getConnection() {
		
		try {
			conn = DriverManager.getConnection( URL+"?user="+Username+"&password="+Password+"&useUnicode=true&characterEncoding=utf-8" ); //解决读取数据库乱码
		} catch (SQLException e) {
			Logger logger=MyLog.getLog("DBConnect");
			logger.error("连接数据库错误:"+e.getMessage());
		}
		return conn;

	}

	// 关闭连接
	public void closeConnection(ResultSet rs, Statement statement,
			Connection con) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			Logger logger=MyLog.getLog("DBConnect");
			logger.error("关闭ResultSet错误:"+e.getMessage());
		} finally {
			try {
				if (statement != null) {
					statement.close();
				}
			} catch (Exception e) {
				Logger logger=MyLog.getLog("DBConnect");
				logger.error("关闭Statement错误:"+e.getMessage());
			} finally {
				try {
					if (con != null) {
						con.close();
					}
				} catch (SQLException e) {
					Logger logger=MyLog.getLog("DBConnect");
					logger.error("关闭Connection错误:"+e.getMessage());
				}
			}
		}
	}

}